package com.link.serve.push.grpc.handler;

import com.alibaba.fastjson2.JSON;
import com.link.serve.constants.LinkRedisKey;
import com.link.serve.push.grpc.ChatMessageProto;
import com.link.serve.tcp.linkdata.SingleUserChannelManager;
import com.link.serve.tcp.message.Message;
import com.link.serve.tcp.process.AbstractMessageProcessor;
import com.link.serve.utils.MessageUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import static com.link.serve.type.IMCmdType.LOGIN;
import static com.link.serve.utils.MessageUtils.buildResponseMessage;

/**
 * 单个消息推送
 * @Author: 杰
 * @Project :link-server
 * @DateTime: 2025-01-25 19:02
 **/
@Component
@Slf4j
public class ChatMessagePushProcessor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 处理单个消息推送
    public void chatMessage(ChatMessageProto.ChatMessage chatMessage) {
        long receiverId = chatMessage.getReceiverId();
        long senderId = chatMessage.getSenderId();
        log.info("解析后的消息内容：{}", chatMessage);
        log.info("准备推送消息，发送方：{}，接收方：{}", senderId, receiverId);

        try {
            // 获取接收方的在线状态
            String key = buildRedisKey(receiverId);

            if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
                Integer serverId = (Integer) redisTemplate.opsForValue().get(key);

                // 判断接收方是否在线
                if (isReceiverOnline(senderId)) {
                    log.info("接收方 {} 在本机，直接推送消息。", receiverId);
                    sendMessageToReceiver(receiverId, chatMessage);
                } else {
                    log.info("接收方 {} 不在本机，转发到服务器 {}", receiverId, serverId);
                    forwardMessageToServer(serverId, chatMessage);
                }
            } else {
                log.warn("接收方 {} 不在线，无法推送消息。", receiverId);
            }
        } catch (Exception e) {
            log.error("消息处理失败，发送方：{}，接收方：{}，错误信息：{}", senderId, receiverId, e.getMessage(), e);
        }
    }

    // 构建 Redis 键
    private String buildRedisKey(long receiverId) {
        return String.join(":", LinkRedisKey.LINK_USER_SERVER_ID, String.valueOf(receiverId));
    }

    // 判断接收方是否在线
    private boolean isReceiverOnline(long senderId) {
        return SingleUserChannelManager.isOnline(senderId);
    }

    // 推送消息给接收方
    private void sendMessageToReceiver(long receiverId, ChatMessageProto.ChatMessage chatMessage) {
        if (SingleUserChannelManager.getChannel(receiverId) != null) {
            //消息推送
            log.info("消息内容为:{}",chatMessage);
            Message message = buildResponseMessage(1, chatMessage.getSenderId(), JSON.toJSONString(chatMessage), chatMessage.getMessageType());
            SingleUserChannelManager.getChannel(receiverId).writeAndFlush(message);
        } else {
            log.error("未找到接收方 {} 的 Channel，无法发送消息", receiverId);
        }
    }
    // 转发消息到指定服务器
    private void forwardMessageToServer(Integer serverId, ChatMessageProto.ChatMessage chatMessage) {
        // 根据服务器 ID 寻找目标服务器并转发消息
        log.info("转发消息到服务器 {}，消息内容：{}", serverId, chatMessage);
        // 实际的转发逻辑可以根据业务需求进一步实现
    }
}
